//
//  YLCEasyVideoListViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/5/7.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCEasyVideoListViewController.h"
#import "YLCVideoTrainCell.h"
#import "ShootVideoViewController.h"
#import "YLCNavigationViewController.h"
#import "YLCSendVideoNextViewController.h"
#define VIDEO_CELL   @"YLCVideoTrainCell"
@interface YLCEasyVideoListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ZFPlayerDelegate,UIActionSheetDelegate>
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@end

@implementation YLCEasyVideoListViewController
{
    UICollectionView *videoTable;
    NSArray *videoDataList;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"添加视频" titleColor:[UIColor whiteColor] selector:@selector(gotoAddVideo) target:self];
}
- (void)gotoAddVideo{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    
    [sheet showInView:self.view];

}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self gotoVideo];
    }
    if (buttonIndex==1) {
        [self gotoAlbum];
    }
}
- (void)gotoVideo{
    ShootVideoViewController *con = [[ShootVideoViewController alloc] init];
    
    con.isEasy = YES;
    
    con.classifyId = _classifyId;
    
    YLCNavigationViewController *nav  = [[YLCNavigationViewController alloc] initWithRootViewController:con];
    
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)gotoAlbum{
    HXAlbumListViewController *con = [[HXAlbumListViewController alloc] init];
    
    HXPhotoManager *manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
    
    manager.configuration.photoMaxNum = 1;
    
    con.manager = manager;
    
    con.doneBlock = ^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL original, HXAlbumListViewController *viewController) {
        HXPhotoModel *photoModel = videoList[0];
        [self getVideoFromPHAsset:photoModel.asset photoModel:photoModel];
    };
    
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:con];
    
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)getVideoFromPHAsset:(PHAsset *)asset
                 photoModel:(HXPhotoModel *)photoModel{
    NSArray *assetResources = [PHAssetResource assetResourcesForAsset:asset];
    PHAssetResource *resource;
    
    for (PHAssetResource *assetRes in assetResources) {
        if (@available(iOS 9.1, *)) {
            if (assetRes.type == PHAssetResourceTypePairedVideo ||
                assetRes.type == PHAssetResourceTypeVideo) {
                resource = assetRes;
            }
        } else {
            // Fallback on earlier versions
        }
    }
    NSString *fileName = @"tempAssetVideo.mov";
    if (resource.originalFilename) {
        fileName = resource.originalFilename;
    }
    
    if (@available(iOS 9.1, *)) {
        if (asset.mediaType == PHAssetMediaTypeVideo || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive) {
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.version = PHImageRequestOptionsVersionCurrent;
            options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
            
            NSString *PATH_MOVIE_FILE = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
            [[NSFileManager defaultManager] removeItemAtPath:PATH_MOVIE_FILE error:nil];
            [[PHAssetResourceManager defaultManager] writeDataForAssetResource:resource
                                                                        toFile:[NSURL fileURLWithPath:PATH_MOVIE_FILE]
                                                                       options:nil
                                                             completionHandler:^(NSError * _Nullable error) {
                                                                 if (error) {
                                                                     
                                                                 } else {
                                                                     
                                                                     NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:PATH_MOVIE_FILE]];
                                                                     YLCSendVideoNextViewController *con = [[YLCSendVideoNextViewController alloc] init];
                                                                     //            PlayVideoViewController* view = [[PlayVideoViewController alloc]init];
                                                                     
                                                                     con.videoPath = photoModel.fileURL;
                                                                     con.classifyId = _classifyId;
                                                                     con.isEasy = YES;
                                                                     con.isAlbum = YES;
                                                                     con.albumVideoData = data;
                                                                     [self.navigationController pushViewController:con animated:YES];
                                                                 }
                                                                 [[NSFileManager defaultManager] removeItemAtPath:PATH_MOVIE_FILE  error:nil];
                                                             }];
        } else {
            
        }
    } else {
        
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSourse];
    [self createCustomView];
}
- (void)initDataSourse{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    [YLCNetWorking loadNetServiceWithParam:@{@"userId":userModel.user_id,@"token":userModel.token,@"classifyId":_classifyId} method:@"POST" urlPath:@"app/sygt/video" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        videoDataList = responseObject;
        
        [videoTable reloadData];
    }];

}
- (void)createCustomView{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 10;
    
    videoTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    videoTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [videoTable registerClass:[YLCVideoTrainCell class] forCellWithReuseIdentifier:VIDEO_CELL];
    
    videoTable.delegate = self;
    
    videoTable.dataSource = self;
    
    [self.view addSubview:videoTable];

    [videoTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (JK_IS_ARRAY_NIL(videoDataList)) {
        return 0;
    }
    return videoDataList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YLCVideoTrainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VIDEO_CELL forIndexPath:indexPath];
    if (indexPath.row<videoDataList.count) {
        cell.dict = videoDataList[indexPath.row];
        WS(weakSelf)
        __block UICollectionView *weakCollectionView = collectionView;
        __block NSDictionary *dict = videoDataList[indexPath.row];
        __block NSIndexPath *weakIndexPath = indexPath;
        __block YLCVideoTrainCell *weakCell     = cell;
        cell.playBlock = ^(UIButton *btn){
            
            
            NSMutableDictionary *dic = @{@"高清":dict[@"site"]}.mutableCopy;
            //        for (ZFVideoResolution * resolution in model.playInfo) {
            //            [dic setValue:resolution.url forKey:resolution.name];
            //        }
            // 取出字典中的第一视频URL
            NSURL *videoURL = [NSURL URLWithString:dict[@"site"]];
            ZFPlayerModel *playerModel = [[ZFPlayerModel alloc] init];
            playerModel.title            = dict[@"title"];
            playerModel.videoURL         = videoURL;
            //        playerModel.placeholderImageURLString = model.coverForFeed;
            playerModel.scrollView       = weakCollectionView;
            playerModel.indexPath        = weakIndexPath;
            // 赋值分辨率字典
            playerModel.resolutionDic    = dic;
            // player的父视图tag
            playerModel.fatherViewTag    = weakCell.posterView.tag;
            
            // 设置播放控制层和model
            [weakSelf.playerView playerControlView:nil playerModel:playerModel];
            // 下载功能
            weakSelf.playerView.hasDownload = NO;
            // 自动播放
            [weakSelf.playerView autoPlayTheVideo];
        };
        
    }
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frameWidth, 212);
}
- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [ZFPlayerView sharedPlayerView];
        _playerView.delegate = self;
        
        _playerView.cellPlayerOnCenter = NO;
        
        _playerView.forcePortrait = NO;
        
        _playerView.stopPlayWhileCellNotVisable = YES;
        
        ZFPlayerShared.isLockScreen = YES;
        ZFPlayerShared.isStatusBarHidden = NO;
    }
    return _playerView;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [[ZFPlayerControlView alloc] init];
    }
    return _controlView;
}
- (NSString *)title{
    return @"视频";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
